#include "ads1258.h"
#include "cppinc/log.h"
#include "bsp.h"

void DrvAds1258::Init()
{
    uint8_t adcConfig[] = { 0x70, 0x12, 0x70,0x00, 0x00, 0xff,0xff,0x00 };
    BspGpioSet(m_ioCs, GPIO_CLR);
    BspDatabusWriteRead(m_dataBus, adcConfig, NULL, sizeof(adcConfig));
    BspGpioSet(m_ioCs, GPIO_SET);
    ReadState();
}

/* 通过读取芯片ID判定对应ADC是否在位 */
void DrvAds1258::ReadState()
{
    uint8_t readIdReg[] = { 0x49, 0xff };
    uint8_t IDReg[2] = { 0 };
    BspGpioSet(m_ioCs, GPIO_CLR);
    BspDatabusWriteRead(m_dataBus, readIdReg, IDReg, sizeof(readIdReg));
    BspGpioSet(m_ioCs, GPIO_SET);

    LOG("ADS slot[%u] adcIdx[%u] ID[%02x] (ADS1258 ID should be 0x8b)", m_slot, m_chipIdx, IDReg[1]);
    m_sta = IDReg[1] == ADC1258_ID_VALID ? ADC_CHIP_RDY : ADC_CHIP_WRONG_ID;
}

void DrvAds1258::ReadChipResult(uint8_t ch, Ads1258Result& result)
{
    for (int ch = 0; ch < ADC1258_CHNL_MAX; ch++) {
        // trigger conver start
        BspGpioSet(m_ioStart, GPIO_SET);
        m_delayus(10);
        BspGpioSet(m_ioStart, GPIO_CLR);

        // wait for conver done
        int32_t timeoutUs = 1000;
        while (--timeoutUs > 0 && BspGpioGet(m_ioRdy) == GPIO_SET) {
            m_delayus(1);
        }
        if (timeoutUs == 0) {
            result.state[ch] = ERR_TIMEOUT;
            continue;
        }

        // read back data
        uint8_t txbuf[5] = { 0x30, 0, 0, 0, 0};
        uint8_t rxbuf[5] = { 0 };
        BspGpioSet(m_ioCs, GPIO_CLR);
        BspDatabusWriteRead(m_dataBus, txbuf, rxbuf, sizeof (txbuf));
        BspGpioSet(m_ioCs, GPIO_SET);

        // return data
        uint32_t regVal = (rxbuf[2] << 24) | (rxbuf[3] << 16) | (rxbuf[4] << 8);
        result.adVal[ch] = (int32_t)regVal / (1 << 8);
        result.state[ch] = rxbuf[1];
    }
}
